import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";

export type CompletionItem = vscode.CompletionItem & {
  importPath: string | undefined;
};

export function compilationFileManager(): CompletionItem[] {
  const uri = vscode.window.activeTextEditor?.document.uri;
  if (uri) {
    const workspaceFolder = vscode.workspace.getWorkspaceFolder(uri)?.uri.fsPath;
    if (workspaceFolder) {
      const config_path = vscode.workspace.getConfiguration().get("Config Path") as string;
      const file = path.join(workspaceFolder, config_path);
      if (fs.existsSync(file)) {
        const data = JSON.parse(fs.readFileSync(file, "utf8"));
        return data;
      }
    }
  }
  return [];
}

class CompletionItemProvider {
  async provideCompletionItems(
    document: vscode.TextDocument,
    position: vscode.Position,
    token: vscode.CancellationToken,
    context: vscode.CompletionContext
  ) {
    const range = new vscode.Range(new vscode.Position(position.line, 0), position);
    const text = document.getText(range);

    if (!/\s*import\s*/gm.exec(text) && !/\s*from\s*/gm.exec(text)) {
      const completionItemList: CompletionItem[] = compilationFileManager().map((item) => ({
        label: item.label,
        kind: 14,
        detail: item.importPath,
        importPath: item.importPath,
      }));
      return completionItemList;
    }
  }

  async resolveCompletionItem(item: CompletionItem, token: vscode.CancellationToken) {
    const line = item.importPath ? `from ${item.importPath} import ${item.label}\n` : `import ${item.label}\n`;
    item.additionalTextEdits = [vscode.TextEdit.insert(new vscode.Position(0, 0), line)];
    return item;
  }
}

export function activate(context: vscode.ExtensionContext) {
  const completionProvider = vscode.languages.registerCompletionItemProvider("python", new CompletionItemProvider());
  context.subscriptions.push(completionProvider);
}
